package handlers

import (
	"article-talk/models"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	comment := c.PostForm("comment")
	if title == "" || comment == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Article{
		Title:   title,
		Comment: comment,
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "发布成功",
		})
		return
	}
}
func List(c *gin.Context) {

	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	count := (page - 1) * size
	var article []models.Article
	err := models.DB.Find(&article).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code":  200,
			"msg":   "展示成功",
			"data":  article,
			"count": count,
		})
		return
	}
}
